package com.kk.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kk.enums.LoginStatus;
import com.kk.mapper.SysLoginLogMapper;
import com.kk.pojo.entity.SysLoginLog;
import com.kk.service.SysLoginLogService;
import com.kk.utils.IpUtils;
import com.kk.utils.VirtualThreadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.time.LocalDateTime;
/**
 * @author kl
 * @version 1.0
 * @description: 登录日志Service实现类
 * @date 2025/10/17 下午5:51
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog>
        implements SysLoginLogService {

    @Override
    public void recordLoginLog(SysLoginLog loginLog) {
        // 使用虚拟线程异步记录日志
        VirtualThreadUtil.runAsync(() -> {
            try {
                this.save(loginLog);
                log.debug("登录日志记录成功: {}", loginLog.getUsername());
            } catch (Exception e) {
                log.error("登录日志记录失败", e);
            }
        });
    }

    @Override
    public void recordLoginSuccess(BigInteger userId, String username, String message) {
        SysLoginLog loginLog = new SysLoginLog()
                .setUsername(username)
                .setUserId(userId)
                .setLoginIp(IpUtils.getIpAddr())
                .setLoginLocation(IpUtils.getLocationByIp(IpUtils.getIpAddr()))
//                .setBrowser(IpUtils.getBrowser())
                .setOs(IpUtils.getOs())
                .setLoginStatus(LoginStatus.SUCCESS.getCode())
//                .setLoginType(LoginType.PASSWORD.getCode())
                .setMessage(message);
        recordLoginLog(loginLog);
    }

    @Override
    public void recordLoginFailure(String username, String message) {
        SysLoginLog loginLog = new SysLoginLog()
                .setUsername(username)
                .setLoginIp(IpUtils.getIpAddr())
                .setLoginLocation(IpUtils.getLocationByIp(IpUtils.getIpAddr()))
//                .setBrowser(IpUtils.getBrowser())
                .setOs(IpUtils.getOs())
                .setLoginStatus(LoginStatus.FAIL.getCode())
//                .setLoginType(LoginType.PASSWORD.getCode())
                .setMessage(message)
                .setLoginTime(LocalDateTime.now());

        recordLoginLog(loginLog);
    }
}